package com.shanghai.shanghaielectric.UI.event;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.shanghai.shanghaielectric.Model.db.ErrorInfoModel;
import com.shanghai.shanghaielectric.R;
import com.shanghai.shanghaielectric.UI.DilaogView.Dialog_Alert;
import com.shanghai.shanghaielectric.UI.refreshView.EndLessOnScrollListener;
import com.shanghai.shanghaielectric.UI.refreshView.MyAdapter_errorInfo;
import com.shanghai.shanghaielectric.UI.refreshView.MyDecoration;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.litepal.crud.DataSupport;
import org.litepal.crud.callback.FindMultiCallback;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * 事件-警告界面
 */
public class EventErrorFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener, OnClickListener {

    @BindView(R.id.bt_clearData)
    Button btClearData;
    Unbinder unbinder;
    private SwipeRefreshLayout mRefreshLayout;
    private RecyclerView mRecyclerView;
    public MyAdapter_errorInfo mAdapter;
    private LinearLayoutManager mLinearLayoutManager;
    private List<ErrorInfoModel> errorInfoModelList;
    public View eventWarningView;
    private RadioGroup tabs_warning_rg;
    private LayoutInflater myInflater;

    private Context mContext;
    Button bt_clearData;

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        System.out.println("EventWarning____onAttach");
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        System.out.println("EventWarning____onCreate");
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        System.out.println("EventWarning____onCreateView");
        eventWarningView = inflater.inflate(R.layout.event_error_fragment, container, false);
        mContext = getActivity().getApplicationContext().getApplicationContext();
//		myInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        initData();
        initView();
//        initListener();
        mLinearLayoutManager = new LinearLayoutManager(mContext);
        mRecyclerView.setLayoutManager(mLinearLayoutManager);
        //添加分隔线
        mRecyclerView.addItemDecoration(new MyDecoration(mContext, MyDecoration.VERTICAL_LIST));
        //为RecyclerView加载Adapter
        mRecyclerView.setAdapter(mAdapter);
        //监听SwipeRefreshLayout.OnRefreshListener
        mRefreshLayout.setOnRefreshListener(this);
        /**
         * 监听addOnScrollListener这个方法，新建我们的EndLessOnScrollListener
         * 在onLoadMore方法中去完成上拉加载的操作
         * */
        mRecyclerView.addOnScrollListener(new EndLessOnScrollListener(mLinearLayoutManager) {
            @Override
            public void onLoadMore(int currentPage) {
//                loadMoreData();
            }
        });
        unbinder = ButterKnife.bind(this, eventWarningView);
        return eventWarningView;
    }

    private void initListener() {

    }

    public void initView() {

        EventBus.getDefault().register(this);
        bt_clearData = (Button) eventWarningView.findViewById(R.id.bt_clearData);

        mRefreshLayout = (SwipeRefreshLayout) eventWarningView.findViewById(R.id.layout_swipe_refresh);
        mRecyclerView = (RecyclerView) eventWarningView.findViewById(R.id.recyclerview);
        mAdapter = new MyAdapter_errorInfo(mContext, errorInfoModelList);

        //这个是下拉刷新出现的那个圈圈要显示的颜色
        mRefreshLayout.setColorSchemeResources(
                R.color.red_color,
                R.color.yellow_color,
                R.color.green_color
        );
//        tabs_warning_rg = (RadioGroup) chartView.findViewById(R.id.tabs_warning_rg);
    }

    //初始化一开始加载的数据
    private void initData() {
//
        errorInfoModelList = new ArrayList<>();
        DataSupport.limit(100).order("errorDate desc").findAsync(ErrorInfoModel.class).listen(new FindMultiCallback() {
            @Override
            public <T> void onFinish(List<T> t) {
//                (ErrorInfoModel)t;
                errorInfoModelList.addAll((List<ErrorInfoModel>) t);
            }
        });//asc 正序


    }

    //每次上拉加载的时候，就加载十条数据到RecyclerView中
    private void loadMoreData() {
        DataSupport.limit(10).offset(10).order("errorDate desc").findAsync(ErrorInfoModel.class).listen(new FindMultiCallback() {
            @Override
            public <T> void onFinish(List<T> t) {
//                (ErrorInfoModel)t;
                errorInfoModelList.addAll((List<ErrorInfoModel>) t);
                mAdapter.notifyDataSetChanged();
            }
        });//asc 正序


//        List<ErrorInfoModel> errorInfoModelList_temp = LitePalHelper.queryErrorInfo();
//        errorInfoModelList.addAll(errorInfoModelList_temp);
////		for (int i =0; i < 10; i++){
////			errorInfoModelList.add("嘿，我是“上拉加载”生出来的"+i);
//        mAdapter.notifyDataSetChanged();
//
//        Toast.makeText(mContext, "上拉数据" + errorInfoModelList.size(), Toast.LENGTH_SHORT).show();
//		}
    }

    /**
     * 重写SwipeRefreshLayout.OnRefreshListener的OnRefresh方法
     * 在这里面去做下拉刷新的操作
     */
    @Override
    public void onRefresh() {
        updateData();
        //数据重新加载完成后，提示数据发生改变，并且设置现在不在刷新
//        mAdapter.notifyDataSetChanged();
//        mRefreshLayout.setRefreshing(false);
    }

    private void updateData() {
        errorInfoModelList.clear();
        DataSupport.limit(100).order("errordate desc").findAsync(ErrorInfoModel.class).listen(new FindMultiCallback() {
            @Override
            public <T> void onFinish(List<T> t) {
//                (ErrorInfoModel)t;
                errorInfoModelList.addAll(0, (List<ErrorInfoModel>) t);
                mAdapter.notifyDataSetChanged();
                mRefreshLayout.setRefreshing(false);
            }
        });//asc 正序
//        List<ErrorInfoModel> errorInfoModelList_temp = LitePalHelper.queryErrorInfo();
//        errorInfoModelList.addAll(0, errorInfoModelList_temp);
//        Toast.makeText(mContext, "下拉刷新，请求数据" + errorInfoModelList.size(), Toast.LENGTH_SHORT).show();
        //我在List最前面加入一条数据
//		errorInfoModelList.add(0, "嘿，我是“下拉刷新”生出来的");
    }


    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        System.out.println("EventWarning____onActivityCreated");
    }

    @Override
    public void onStart() {
        super.onStart();
        System.out.println("EventWarning____onStart");
    }

    @Override
    public void onResume() {
        super.onResume();
updateData();
//        DataSupport.limit(100).order("errorDate desc").findAsync(ErrorInfoModel.class).listen(new FindMultiCallback() {
//            @Override
//            public <T> void onFinish(List<T> t) {
////                (ErrorInfoModel)t;
//                errorInfoModelList.clear();
//                errorInfoModelList.addAll(0, (List<ErrorInfoModel>) t);
//                mAdapter.notifyDataSetChanged();
//
//
//            }
//        });//asc 正序
        System.out.println("EventWarning____onResume");
    }

    @Override
    public void onPause() {
        super.onPause();

        System.out.println("EventWarning____onPause");
    }

    @Override
    public void onStop() {
        super.onStop();
        System.out.println("EventWarning____onStop");
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        System.out.println("EventWarning____onDestroyView");
        unbinder.unbind();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);

        System.out.println("EventWarning____onDestroy");
    }

    @Override
    public void onDetach() {
        super.onDetach();
        System.out.println("EventWarning____onDetach");
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {

            case R.id.bt_clearData:

                break;
        }
    }

    //    ReceiveDataHelper.Error_DataListener error_dataListener = new ReceiveDataHelper.Error_DataListener() {
//        @Override
//        public void onDataChangde() {
//            DataSupport.limit(100).order("errorDate desc").findAsync(ErrorInfoModel.class).listen(new FindMultiCallback() {
//                @Override
//                public <T> void onFinish(List<T> t) {
////                (ErrorInfoModel)t;
//                    errorInfoModelList.clear();
//                    errorInfoModelList.addAll(0, (List<ErrorInfoModel>) t);
//                    mAdapter.notifyDataSetChanged();
//                }
//            });//asc 正序
//        }
//    };

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onErrorInfoChanged(ErrorInfoModel errorInfoModel) {
        updateData();
//        DataSupport.limit(100).order("errorDate desc").findAsync(ErrorInfoModel.class).listen(new FindMultiCallback() {
//            @Override
//            public <T> void onFinish(List<T> t) {
////                (ErrorInfoModel)t;
//                errorInfoModelList.clear();
//                errorInfoModelList.addAll(0, (List<ErrorInfoModel>) t);
//                mAdapter.notifyDataSetChanged();
//            }
//        });//asc 正序
    }


    private void showDiolg(String commandName) {
        Dialog_Alert diolgAlert = new Dialog_Alert();
        diolgAlert.setCommandName(commandName);
        diolgAlert.show(this.getFragmentManager(), "");
    }

    @OnClick(R.id.bt_clearData)
    public void onViewClicked() {
        showDiolg("是否清空故障记录数据？");
        Dialog_Alert.setDiolgAlertListener(new Dialog_Alert.DialogAlertListener() {
            @Override
            public void onClink(boolean flag) {
                if (flag) {
                    DataSupport.deleteAll(ErrorInfoModel.class);
                    Toast.makeText(mContext, "已删除...", Toast.LENGTH_SHORT).show();
                    updateData();
                }
            }
        });
    }
}
